package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import java.util.Objects;

import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.ModelDeploymentContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.enums.ModelCategoryEnum;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.ModelDeploymentPostProcessor;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Processor - 模型部署后，更新模型的状态
 *
 * @author lilh
 * @date 2021/4/26 14:34
 */
@Component
public class UpdateModelCategoryProcessor implements ModelDeploymentPostProcessor {

    @Autowired
    private RepositoryService repositoryService;

    @Override
    public void process(ModelDeploymentContext context) {
        updateModelCategory(context.getModel(), context.getDeployId());
    }

    private void updateModelCategory(Model model, String deployId) {
        if(null==model){
            return;
        }
        //1.将运行中的更新为历史
        Model runningModel = repositoryService.createModelQuery().modelKey(model.getKey()).modelCategory(ModelCategoryEnum.RUNNING.getCode()).singleResult();
        if (Objects.nonNull(runningModel)) {
            runningModel.setCategory(ModelCategoryEnum.HISTORY.getCode());
            repositoryService.saveModel(runningModel);
        }

        //2.将部署好的模型设置为运行状态
        model.setCategory(ModelCategoryEnum.RUNNING.getCode());
        model.setDeploymentId(deployId);
        repositoryService.saveModel(model);

    }
}
